<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               v-if="showMain"
    >
      <template slot="menuLeft" slot-scope="{type,size,row,index}">
<!--        <el-button type="danger"-->
<!--                   size="small"-->
<!--                   icon="el-icon-delete"-->
<!--                   plain-->
<!--                   @click="handleDelete">删 除-->
<!--        </el-button>-->
        <el-button type="warning" icon="el-icon-back" size="small" @click.stop="goBack()">返回列表</el-button>

        <el-dialog title="查看" :visible.sync="parentDialogVisible" width="45%" :before-close="handleClose">
          <div class="optList">
            <div class="optListp">
              <label>标题:</label>
              <el-input v-model="parentDialogDetails.title" placeholder="请输入标题" size="small" :disabled="dialogDisabled"></el-input>
            </div>
            <div class="optListp" style="margin-top: 20px">
              <label>类别:</label>
              <el-select v-model="parentDialogDetails.type" filterable placeholder="请选择责任老师" size="small"
                         @change="handleCheckedCitiesChange" :disabled="true">
                <el-option v-for="item in category" :key="item.value" :label="item.label" :value="item.value" >
                </el-option>
              </el-select>
            </div>
            <div class="optListp" style="margin-top: 20px">
              <label>排序:</label>
              <el-input-number :min="0" v-model="parentDialogDetails.sort" placeholder="请输入排序" size="small" :disabled="dialogDisabled"></el-input-number>
            </div>

          </div>
          <span slot="footer" class="dialog-footer" v-if="isDialogFooter">
            <el-button @click="parentDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="parentSubmit">确 定</el-button>
          </span>
        </el-dialog>


        <el-dialog title="新增子项" :visible.sync="dialogVisible" width="45%" :before-close="handleClose">
          <div class="optList">
            <div class="optListp" v-if="isContent" >
              <label>内容:</label>
              <el-input v-model="dialogDetails.content" placeholder="请输入标题" size="small" :disabled="dialogDisabled"></el-input>
            </div>
            <div class="optListp" style="margin-top: 20px">
              <label>排序:</label>
              <el-input-number :min="0" v-model="dialogDetails.sort" placeholder="请输入排序" size="small" :disabled="dialogDisabled"></el-input-number>
            </div>
            <div class="optListp" v-if="!isContent" style="margin-top: 20px">
              <label>所获奖项:</label>
              <el-upload
                :disabled="dialogDisabled"
                class="avatar-uploader"
                action="/api/localfiles/uploadPcFile"
                accept="image/*"
                :show-file-list="false"
                :headers = headers
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>


          </div>
          <span slot="footer" class="dialog-footer" v-if="isDialogFooter">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="amend(row)">确 定</el-button>
          </span>
        </el-dialog>

      </template>
      <template slot-scope="{type,size,row,index}" slot="menuBtn">
        <el-dropdown-item  @click.native="detailsClick(row)">查看</el-dropdown-item>
        <el-dropdown-item  divided @click.native="editClick(row,'edit')">编辑</el-dropdown-item>
        <el-dropdown-item  divided @click.native="delClick(row)">删除</el-dropdown-item>
        <el-dropdown-item v-if="!row.isChildren" divided @click.native="showView(row,'add')">新增子项</el-dropdown-item>
      </template>

<!--      <template slot="menuLeft">-->
<!--        <el-button type="warning" icon="el-icon-back" size="small" @click.stop="goBack()">返回列表</el-button>-->
<!--      </template>-->
    </avue-crud>
    <JsJsnr v-bind:nrId="nrId" v-bind:appUserId="csId" :showMainView="showMainView1" v-if="(!showMain)&&show1"
            ref="eps1"></JsJsnr>
    <JsJstp v-bind:nrId="nrId" v-bind:appUserId="csId" :showMainView="showMainView2" v-if="(!showMain)&&show2"
            ref="eps1"></JsJstp>
  </basic-container>
</template>

<script>
import {getList, add, update, remove, profileAdd, imgAdd, removeDel} from "@/api/service/jsJsfc";
import {mapGetters} from "vuex";
import JsJsnr from "@/views/service/jsJsnr.vue";
import JsJstp from "@/views/service/jsJstp.vue";
import {getToken} from '@/util/auth'

export default {
  components: {
    JsJsnr,
    JsJstp
  },
  props: {
    csId: {
      type: String,
      default: '0'
    }, showMainView: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      showMain: true,
      show1: false,
      show2: false,
      parentDialogVisible:false,
      parentDialogDetails:{},
      dialogDetails:{},
      dialogVisible: false,
      dialogDisabled:false,
      isDialogFooter:true,
      isContent: true,
      headers:{},
      nrId: '',
      form: {},
      query: {},
      loading: true,
      imageUrl: '',
      category: [{
        label: "个人简历",
        value: 1
      },
        {
          label: "所获奖项",
          value: 2
        }],
      categoryName: '',
      categoryId: '',
      content: '',
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "标题",
            prop: "title",
            overHidden: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入章节名称",
              trigger: "blur"
            }],
          },
          {
            label: "类别",
            prop: "type",
            overHidden: true,
            span: 24,
            rules: [{
              required: true,
              message: "请选择课程难度",
              trigger: "blur"
            }],
            type: "select",
            dicData: [
              {
                label: "个人简历",
                value: 1
              },
              {
                label: "所获奖项",
                value: 2
              }
            ],
            // dataType: "string",
          },
          {
            label: "排序",
            prop: "sort",
            overHidden: true,
            type: "number",
            span: 24,
            rules: [{
              required: true,
              message: "请输入排序",
              trigger: "blur"
            }],
          },


        ]
      },
      data: []
    };
  },
  created() {
    this.headers = {
      'Blade-Auth':'bearer ' + getToken()
    }
  },
  computed: {
    ...mapGetters(["permission", "JSuserInfo"]),
    permissionList() {
      return {
        addBtn: true,//this.vaildData(this.permission.jkcsevaluate_add, false),
        viewBtn: false,//this.vaildData(this.permission.jkcsevaluate_view, true),
        delBtn: false,//this.vaildData(this.permission.jkcsevaluate_delete, true),
        editBtn: false,//this.vaildData(this.permission.jkcsevaluate_edit, true)
      };
    },
    jsId() {
      return this.JSuserInfo.js_Id
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    goBack() {
      this.showMainView();
    },
    rowSave(row, done, loading) {
      row.id = row.id === '' ? '0' : row.id
      row.AppUserId = this.csId;
      row.js_id = this.csId;//教师id
      row.tenant_id = '' //租户 id
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      row.csId = this.csId;

      update(row).then(() => {
        // done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.parentDialogVisible = false
      }, error => {
        this.parentDialogVisible = false
        window.console.log(error);
        loading();
      });
    },
    // 父类删除
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id, AppUserId: this.csId});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    // 子类删除
    rowDel1(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeDel({ids: row.id, AppUserId: this.csId});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids, AppUserId: this.csId});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.AppUserId = this.csId;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.totalItems;
        this.data = data.items;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 查看
    detailsClick(row){
      console.log('111111111',row)
      if(row.isChildren){
        //子级
        this.imageUrl = row.url
        this.dialogDetails = row
        this.isContent = row.type == 1 ? true : false
        this.isDialogFooter = false
        this.dialogDisabled = true
        this.dialogVisible = true

      }else {
       //父级
        this.parentDialogDetails = row
        this.dialogDisabled = true
        this.isDialogFooter = false
        this.parentDialogVisible = true
      }
    },
    // 编辑
    editClick(row,btnType){
      console.log(row)
      if(row.isChildren){
        //子级
        this.imageUrl = row.url
        row.btnType = btnType
        this.dialogDetails = row
        this.isContent = row.type == 1 ? true : false
        this.isDialogFooter = true
        this.dialogDisabled = false
        this.dialogVisible = true
      }else {
        //父级
        this.parentDialogDetails = row
        this.dialogDisabled = false
        this.isDialogFooter = true
        this.parentDialogVisible = true
      }
    },
    // 删除
    delClick(row){
      if(row.isChildren){
        //子级
        this.dialogDetails = row
        this.rowDel1(this.dialogDetails)
      }else {
        //父级
        this.parentDialogDetails = row
        this.rowDel(this.parentDialogDetails)
      }
    },
    // 父级弹窗确定
    parentSubmit(){
      this.rowUpdate(this.parentDialogDetails)
    },

    showView(row,btnType) {
      console.log(row)
      row.btnType = btnType
      this.isContent = row.type == 1 ? true : false
      this.dialogDetails = row
      this.nrId = row.id;
      this.isDialogFooter = true
      this.dialogDisabled = false
      this.imageUrl = ''
      this.dialogDetails.sort = 0
      this.dialogVisible = true
    },
    showMainView1() {
      this.showMain = true;
      this.show1 = false;
      this.show2 = true
    },
    showMainView2() {
      this.showMain = true;
      this.show1 = true;
      this.show2 = false;
    },
    handleCheckedCitiesChange(e) {
      this.categoryId = e
    },
    // 子级编辑/新增接口 内容
    rowEditClick(row){
      profileAdd(row).then(res => {
        if (res.data.code == 0) {
          this.dialogVisible = false
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.onLoad(this.page)
        } else {
          this.$message({
            message: '修改失败',
            type: 'error'
          });
        }
      })
    },
    // 子级编辑/新增接口 图片
    rowEditClick1(row){
      imgAdd(row).then(res => {
        if (res.data.code == 0) {
          this.dialogVisible = false
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.onLoad(this.page)
        } else {
          this.$message({
            message: '修改失败',
            type: 'error'
          });
        }
      })
    },
    // rowEditClick(row){
    //   row.AppUserId = this.csId;
    //   row.parentId = this.dialogDetails.id;
    //   row.tenant_id = '' //租户 id
    //   row.content = this.dialogDetails.title
    //   if (this.dialogDetails.type == 1) {
    //     // 简介
    //
    //     this.content = ""
    //   } else {
    //     // 图片  url
    //     imgAdd(row).then(res => {
    //       if (res.data.code == 0) {
    //         this.dialogVisible = false
    //         this.$message({
    //           message: '修改成功',
    //           type: 'success'
    //         });
    //         this.onLoad(this.page)
    //       } else {
    //         this.$message({
    //           message: '修改失败',
    //           type: 'error'
    //         });
    //       }
    //     })
    //     this.content = ""
    //   }
    // },
    // 新增子项/编辑确定
    amend() {
      if(this.dialogDetails.type == 1){
        // 个人简历
        this.dialogDetails.tenant_id = '';
        this.dialogDetails.AppUserId = this.csId;
        if(this.dialogDetails.btnType == 'edit'){
          this.dialogDetails.parentId = this.dialogDetails.parentId;
        }else {
          this.dialogDetails.parentId = this.dialogDetails.id
          this.dialogDetails.id = 0
        }
        this.rowEditClick(this.dialogDetails)
      }else {
        // 所获奖项
        this.imageUrl = this.dialogDetails.url;
        this.dialogDetails.tenant_id = '';
        this.dialogDetails.AppUserId = this.csId;
        if(this.dialogDetails.btnType == 'edit'){
          this.dialogDetails.parentId = this.dialogDetails.parentId;
        }else {
          this.dialogDetails.parentId = this.dialogDetails.id
          this.dialogDetails.id = 0
        }
        this.rowEditClick1(this.dialogDetails)
      }

      // let data = {
      //   content: this.content,
      //   id: '0',
      //   AppUserId: this.csId,
      //   parentId: this.nrId,
      //   tenant_id: '',
      // }
      // if (this.dialogDetails.type == 1) {
      //   // 简介
      //   profileAdd(data).then(res => {
      //     if (res.data.code == 0) {
      //       this.dialogVisible = false
      //       this.$message({
      //         message: '修改成功',
      //         type: 'success'
      //       });
      //       this.onLoad(this.page)
      //     } else {
      //       this.$message({
      //         message: '修改失败',
      //         type: 'error'
      //       });
      //     }
      //   })
      //   this.content = ""
      // } else {
      //   // 图片  url
      //   data.url = this.imageUrl
      //   delete data.content
      //   imgAdd(data).then(res => {
      //     if (res.data.code == 0) {
      //       this.dialogVisible = false
      //       this.$message({
      //         message: '修改成功',
      //         type: 'success'
      //       });
      //       this.onLoad(this.page)
      //     } else {
      //       this.$message({
      //         message: '修改失败',
      //         type: 'error'
      //       });
      //     }
      //   })
      //   this.content = ""
      // }
    },
    handleAvatarSuccess(res) {
      console.log(res)
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.dialogDetails.url = res.data.link;
      this.imageUrl = res.data.link;
      console.log('url',this.dialogDetails.url)
    },
    beforeAvatarUpload(file) {
      console.log(file)
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;
      //
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
    }
  }
};
</script>

<style>
.optList {
  /*display: flex;*/
  /*justify-content: space-between;*/
  width: 90%;
}

.optListp {
  width: 100%;
  display: flex;
}

.optListp label {
  width: 70px;
  line-height: 30px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
